var express = require('express');
var router = express.Router();
var User = require("./db/UserDB");
var Article = require("./db/Article");
var Leave = require("./db/Leave");
var ChatMsg = require("./db/ChatMsg");
const {
  validate,
  register_validate
} = require("../public/js/validate");

router.get('/', async function(req, res, next) {
  // await Article.remove();
  res.locals.msg = req.session.msg;
  req.session.msg = "";
  let user = req.session.user ? req.session.user : "";
  const list = await Article.find()
    .select("-body")
    .sort("-createData");
  res.locals.user = user;
  res.render('index', {list});
});

router.get('/login/:param', function(req, res) {
  if (req.params.param == "login") {
    res.render('login', {
      title: '登录'
    });
  } else if (req.params.param == "register") {
    res.render('login', {
      title: '注册'
    });
  } else if (req.params.param == 'exit') {
    req.session.user = "";
    res.redirect("/");
  }
})

router.post("/login", async function(req, res) {
  const {
    name,
    password,
    confirm_password
  } = req.body;
  if ("confirm_password" in req.body) { //注册 obj.hasOwnProperty('name');判断对象包含某个属性
    let errors = register_validate(name, password, confirm_password);
    if (Object.keys(errors).length == 0) {
      let user = await User.findOne({name});
      if (user) {
        errors.name = "用户名已存在";
        res.send(errors);
      }else {
        let u= new User({
          name,
          password,
          role: "ordinary"
        });
        u.save();
        req.session.user = {name, password,  role: "ordinary"};
        res.send({
          success: "成功了"
        });
      }
    }else {
      res.send(errors);
    }
  } else {
    let errors = validate(name, password);
    if (Object.keys(errors).length == 0) {
      let user = await User.findOne({name});
      if (!user) {
        errors.name = "用户名不存在";
      }else if (user.password != password) {
          errors.password = "密码错误";
      }else {
        req.session.user = {name, password};
        res.send({success: "成功了"});
        return;
      }
    }
    res.send(errors);
  }
});


// 打开创建文章页面
router.get("/create",function (req,res) {
  let user = req.session.user;
  if (user) {
    res.render("createArticle", {article:null});
  }else {
    req.session.msg = "请登录";
    res.redirect('back');
  }
});

// 创建文章
router.post("/create",async function (req,res) {
  req.session.user;
  const {title , content} = req.body;
  const doc = new Article({
    title,content,
    createData:new Date(),
    auther: req.session.user.name
  });
  await doc.save();
  res.redirect("/");
});

// 删除
router.get("/:id/delete",async function (req,res) {
  await Article.remove({_id:req.params.id});
  res.redirect("/");
});

// 更改
router.get("/:auther/:id/edit",async function (req,res) {
  let user = req.session.user;
  let auther;
  if (user && user.name == req.params.auther) {
    auther = req.params.auther;
  }else {
    auther = "";
  }
  let article = await Article.findById(req.params.id);
  res.render("createArticle",{article,auther});
});


// 更改
router.post("/update/:id",async function (req,res) {
  const id = req.params.id;
  const {title,content} = req.body;
  const doc = await Article.findById(id);
  if(doc){
    doc.title = title;
    doc.content = content;
    await doc.save();
  }
  res.redirect("/");
})

//导航留言
router.get("/leave_nav", async function (req, res) {
  // await Leave.remove();
  let leaveMsgs = await Leave.find().sort("-createData");
  res.send({leaveMsgs});
})

//留言
router.get("/submit_leave", function (req, res) {
  let auther = req.session.user.name;
  const {leave} = req.query;
  let msg = new Leave({
    auther,
    msg:leave,
    createData:new Date()
  });
  msg.save();
  // let leaveMsgs = Leave.find()
  //   .sort("-createData");
  res.send({msg});
})


//聊天室
router.get("/chat_nav", async function (req, res) {
  await ChatMsg.remove();
  let user = req.session.user;
  let chatMsgs = await ChatMsg.find().sort("createData");
  res.send({chatMsgs,user});
})

module.exports = router;
